import { ChatOpenAI } from '@langchain/openai';
import { FRIDAY_LLM_CONFIG } from './constants';
import {
  ChatPromptTemplate,
  MessagesPlaceholder,
} from '@langchain/core/prompts';
import { createOpenAIFunctionsAgent, AgentExecutor } from 'langchain/agents';
import { StructuredToolInterface } from '@langchain/core/tools';
import { TavilySearchResults } from '@langchain/community/tools/tavily_search';

import { createInterface } from 'readline';

// import { TavilySearch } from '@langchain/tavily';
export async function agent() {
  const model = new ChatOpenAI({
    verbose: true, // 控制台日志
    model: 'gpt-4.1',
    temperature: 0.9,
    configuration: {
      baseURL: FRIDAY_LLM_CONFIG.API_BASE_URL,
      apiKey: FRIDAY_LLM_CONFIG.API_KEY,
    },
    // maxTokens: 8000,
  });

  const prompt = ChatPromptTemplate.fromMessages([
    ['system', '有什么可以帮你的吗？'],
    new MessagesPlaceholder('chat_history'),
    ['human', '{input}'],
    new MessagesPlaceholder('agent_scratchpad'),
  ]);
  //https://app.tavily.com/home
  const searchTool = new TavilySearchResults({
    apiKey: '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',
  });
  const tools: StructuredToolInterface[] = [searchTool];
  // const tool = new TavilySearch({
  // maxResults: 3,
  // tavilyApiKey: 'YOUR_API_KEY',
  // });
  // const results = await tool.invoke({ query: 'latest AI news' });
  // const tools: StructuredToolInterface[] = [tool];
  const agent = await createOpenAIFunctionsAgent({
    llm: model,
    prompt,
    tools,
    // streamRunnable,
  });

  //代理执行器
  const agentExecutor = new AgentExecutor({
    agent,
    tools,
  });

  // function askQuestion(question: string) {
  //   return agentExecutor.invoke({ input: question });
  // }
  const rl = createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('请输入问题：', async (question) => {
    const response = await agentExecutor.invoke({ input: question });
    console.log(response);
    // rl.close();
  });
  // return await agentExecutor.invoke({ input: 'hello' });
}
agent();
